/**
 * @Author: jinye
 * @Date:   2016-02-24 15:19:59
 */

'use strict';

/*
 |--------------------------------------------------------------------------
 | 依赖模块
 |--------------------------------------------------------------------------
 */

var path                = require('path');
var webpack             = require('webpack');
var ExtractTextPlugin   = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin   = require('html-webpack-plugin');

/*
 |--------------------------------------------------------------------------
 | 资源路径信息
 |--------------------------------------------------------------------------
 */

var ROOT_PATH           = path.join(__dirname, 'src');
var DIST_PATH           = path.join(__dirname, 'dist');
var NODE_MODULE_PATH    = path.join(__dirname, 'node_modules');

console.log(ROOT_PATH)

/*
 |--------------------------------------------------------------------------
 | webpack 配置
 |--------------------------------------------------------------------------
 */

module.exports = function(options) {

    // 依赖 gulp 任务传入参数
    var DEBUG = options.debug;

    // 指定图片转换成BASE64的最大比特数
    // 当图片大小小于指定比特数时转换为BASE64以减少请求数，否则直接使用图片文件
    var BASE64_LIMIT = 2048;

    // 定义标记 用于区分开发和发布代码
    var FLAGS = {
        '__DEBUG__': DEBUG
    }

    // HTML MINI 参数
    var minimizeOptions = {
        conservativeCollapse: false,
        preserveLineBreaks: false
    };
    
    var CONFIG = {

        devtool: DEBUG ? 'inline-source-map' : 'source-map',

        //入口，可以是一个或者多个资源合并而成，由html通过script标签引入
        entry : {
            app : DEBUG ? [
                'webpack/hot/dev-server',
                'webpack-hot-middleware/client?reload=true',
                ROOT_PATH + '/app.js'
            ] : [ROOT_PATH + '/app.js']
           // vendor: ["angular-cookies"/*"jquery","angular","angular-resource","angular-ui-router","angular-cookies","angular-sanitize","angular-animate","angular-ui-bootstrap","angular-local-storage","ui-select"*/]
        },

        output: {
            path : DIST_PATH,
            filename: DEBUG ? 'scripts/[name].js' : 'scripts/[name].[hash:8].js',
            publicPath: DEBUG ? '' : '../'
        },

        module: {
            loaders: [
                {
                    test: /\.css$/,
                    loader: DEBUG ? 'style!css' :  ExtractTextPlugin.extract('css?minimize')
                },
                {
                    test: /\.scss$/,
                    loader: DEBUG ? 'style!css!autoprefixer!sass' : ExtractTextPlugin.extract('css!autoprefixer!sass')
                },
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: "ng-annotate!babel?presets[]=es2015"
                },
                {
                    test: /\.view\.html$/,
                    loader: 'ngtemplate?relativeTo=' + ROOT_PATH + '/pages!html'
                },
                {
                    test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url?name=fonts/[name].[ext]&limit=10000&mimetype=application/font-woff&prefix=fonts'
                },
                {
                    test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url?name=fonts/[name].[ext]&limit=10000&mimetype=application/octet-stream&prefix=fonts'
                },
                {
                    test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url?name=fonts/[name].[ext]&limit=10000&mimetype=application/vnd.ms-fontobject&prefix=fonts'
                },
                {
                    test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url?name=fonts/[name].[ext]&limit=10000&mimetype=image/svg+xml&prefix=fonts'
                },
                {
                    test: /\.png/,
                    loader: 'url?name=images/[name]_[hash:8].[ext]&limit=' + BASE64_LIMIT + '&mimetype=image/png&context=./src'
                },
                {
                    test: /\.jpg/,
                    loader: 'url?name=images/[name]_[hash:8].[ext]&limit=' + BASE64_LIMIT + '&mimetype=image/jpg'
                },
                {
                    test: /\.gif/,
                    loader: 'url?name=images/[name]_[hash:8].[ext]&limit=' + BASE64_LIMIT + '&mimetype=image/gif'
                }
            ]
        },

        resolve: {
            root: [ROOT_PATH, NODE_MODULE_PATH],
            alias: {},
            extensions: ['', '.js', '.json']
        },

        resolveLoader: {
            noParse: [],
            modulesDirectories: [NODE_MODULE_PATH]
        },

        plugins : [
            // 优化模块加载顺序
            new webpack.optimize.OccurenceOrderPlugin(true),

            // 变量定义，以便在开发阶段使用
            new webpack.DefinePlugin(FLAGS),

            // Reference: https://github.com/ampedandwired/html-webpack-plugin
            new HtmlWebpackPlugin({
                template: ROOT_PATH + '/index.html',
                filename: DEBUG ? 'index.html' : './index.html',
                inject: "body"
            })

        ].concat(DEBUG ? [
            // 代码热替换
            new webpack.HotModuleReplacementPlugin(),

            // 禁止调试模式报错
            new webpack.NoErrorsPlugin()
        ] : [

            // 抽取 CSS 到独立的文件
            new ExtractTextPlugin('css/[name].[hash:8].min.css',{
                allChunks: true
            }),

            //new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"scripts/vendors.[hash:8].js"),

            new webpack.optimize.DedupePlugin(),

            // 代码压缩
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false
                }
            }),
            // 最大限度地合并相似模块
            new webpack.optimize.AggressiveMergingPlugin()
        ])
    }
    return CONFIG;
}